package com.lzy.cloud.push.umeng.base;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;

@Component
public class PushClient {

    @Autowired
    private UMengConfig uMengConfig;

    private final static Logger LOGGER = LoggerFactory.getLogger(PushClient.class);


    // This object is used for sending the post request to Umeng
    protected HttpClient client = HttpClients.createDefault();


    public String send(UmengNotification msg) throws Exception {
        String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
        msg.setPredefinedKeyValue("timestamp", timestamp);
        String url = uMengConfig.getHost() + uMengConfig.getPostPath();
        String postBody = msg.getPostBody();
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(postBody);
        String sign = "";
        if (msg instanceof AndroidNotification) {
            jsonObject.put("appkey", uMengConfig.getAppKey());
            sign = DigestUtils.md5Hex(("POST" + url + jsonObject + uMengConfig.getMasterSecret()).getBytes("utf8"));
        }
        if (msg instanceof IOSNotification) {
            jsonObject.put("appkey", uMengConfig.getIosAppKey());
            sign = DigestUtils.md5Hex(("POST" + url + jsonObject + uMengConfig.getIosAppMasterSecret()).getBytes("utf8"));
        }
        url = url + "?sign=" + sign;
        LOGGER.info("uMeng post url---" + url.toString());
        LOGGER.info("uMeng post body---" + jsonObject.toJSONString());
        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", uMengConfig.getUSER_AGENT());
        StringEntity se = new StringEntity(jsonObject.toString(), "UTF-8");
        post.setEntity(se);
        // Send the post request and get the response
        HttpResponse response = client.execute(post);
        int status = response.getStatusLine().getStatusCode();
        LOGGER.info("Response Code : " + status);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        LOGGER.info(result.toString());
        if (status == 200) {
            LOGGER.info("Success to send the notification!");
        } else {
            LOGGER.info("Failed to send the notification!");
        }
        return result.toString();
    }

    // Upload file with device_tokens to Umeng
    //todo
    public String uploadContents(String appkey, String appMasterSecret, String contents) throws Exception {
        // Construct the json string
        JSONObject uploadJson = new JSONObject();
        uploadJson.put("appkey", appkey);
        String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
        uploadJson.put("timestamp", timestamp);
        uploadJson.put("content", contents);
        // Construct the request
        String url = uMengConfig.getHost() + uMengConfig.getPostPath();
        String postBody = uploadJson.toString();
        String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes("utf8"));
        url = url + "?sign=" + sign;
        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", uMengConfig.getUSER_AGENT());
        StringEntity se = new StringEntity(postBody, "UTF-8");
        post.setEntity(se);
        // Send the post request and get the response
        HttpResponse response = client.execute(post);
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        System.out.println(result.toString());
        // Decode response string and get file_id from it
        JSONObject respJson = new JSONObject(result.toString());
        String ret = respJson.getString("ret");
        if (!ret.equals("SUCCESS")) {
            throw new Exception("Failed to upload file");
        }
        JSONObject data = respJson.getJSONObject("data");
        String fileId = data.getString("file_id");
        // Set file_id into rootJson using setPredefinedKeyValue

        return fileId;
    }

}
